package service

import (
	"context"
	"errors"
	__ "shop-microservices/basic/goods_proto"
	"shop-microservices/handler/dao"
)

type Server struct {
	__.UnimplementedGoodsServer
}

// 清空购物车
func (s *Server) CleanShopCar(_ context.Context, in *__.CleanShopCarReq) (*__.CleanShopCarResp, error) {
	err := dao.CleanShopCar(in.UserId)
	if err != nil {
		return nil, errors.New("购物车清空失败" + err.Error())
	}
	return &__.CleanShopCarResp{}, nil
}

// 添加购物车
func (s *Server) AddShopCar(_ context.Context, in *__.AddShopCarReq) (*__.AddShopCarResp, error) {
	err := dao.SetInShoCar(in)
	if err != nil {
		return nil, err
	}
	return &__.AddShopCarResp{}, nil
}

// 增加购物车记载数量
func (s *Server) AddShopCarNum(_ context.Context, in *__.AddShopCarNumReq) (*__.AddShopCarNumResp, error) {
	err := dao.AddShopCarNum(in)
	if err != nil {
		return nil, err
	}
	return &__.AddShopCarNumResp{}, nil
}

// 扣减购物车记载数量
func (s *Server) PopShopCarNum(_ context.Context, in *__.PopShopCarNumReq) (*__.PopShopCarNumResp, error) {
	err := dao.PopShopCarNum(in)
	if err != nil {
		return nil, err
	}
	return &__.PopShopCarNumResp{}, nil
}

// 修改购物车记在数量
func (s *Server) UpdateShopCarNum(_ context.Context, in *__.UpdateShopCarNumReq) (*__.UpdateShopCarNumResp, error) {
	res := dao.UpdateShopCarData(in.UserId, in.GoodsId, in.Num, "num")

	if res != nil {
		return nil, res
	}

	g, err := dao.GetGoodsById(in.GoodsId)
	if err != nil {
		return nil, err
	}

	newPrice := float64(in.Num) * g.GoodsPrice
	err = dao.UpdateShopCarData(in.UserId, in.GoodsId, newPrice, "price")
	// 修改mysql购物车
	err = dao.GetByUserIdAndGoodsIdWithUpdatePriceAndNum(in.UserId, in.GoodsId, in.Num, newPrice)
	if err != nil {
		return nil, errors.New("mysql修改购物车失败" + err.Error())
	}
	return &__.UpdateShopCarNumResp{}, nil
}

// 获取购物车未支付商品的总价
func (s *Server) GetShopCarAllPrice(_ context.Context, in *__.GetShopCarAllPriceReq) (*__.GetShopCarAllPriceResp, error) {
	price := dao.GetShopCarTotalPrice(in.UserId)
	return &__.GetShopCarAllPriceResp{Price: float32(price)}, nil
}

// 购物车列表
func (s *Server) UserShopCarList(_ context.Context, in *__.UserShopCarListReq) (*__.UserShopCarListResp, error) {
	list, err := dao.GetShopCarList(in.UserId)
	if err != nil {
		return nil, err
	}
	return &__.UserShopCarListResp{List: list}, nil
}

// 根据商品名查redis 购物车数据
func (s *Server) UserSearchShopCarByName(_ context.Context, in *__.UserSearchShopCarByNameReq) (*__.UserSearchShopCarByNameResp, error) {
	list, err := dao.UserSearchShopCarByName(in)
	if err != nil {
		return nil, err
	}
	return &__.UserSearchShopCarByNameResp{List: list}, nil
}

// 删除某项购物车数据
func (s *Server) DelOneShopCarData(_ context.Context, in *__.DelOneShopCarDataReq) (*__.DelOneShopCarDataResp, error) {
	err := dao.DelShopCarData(in.UserId, in.GoodsId)
	if err != nil {
		return nil, err
	}
	err = dao.DelByUserIdAndGoodsIdInMysql(in.UserId, in.GoodsId)
	if err != nil {
		return nil, err
	}
	return &__.DelOneShopCarDataResp{}, nil
}
